package com.drive.service.serviceimpl;

import com.drive.bean.Subject;
import com.drive.entity.PageResult;
import com.drive.mapper.SubjectMapper;
import com.drive.service.SubjectService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 往
 * 科目管理实现类
 */
@Service
public class SubjectServiceImpl implements SubjectService {
    @Autowired
    private SubjectMapper subjectMapper;
    @Override
    public void add(Subject subject, Integer[] coachIds) {
        //添加科目信息
        subjectMapper.add(subject);
        //绑定科目于教练之间的多对多关系
        if(coachIds!=null&&coachIds.length>0){
            setSubjectAndCoach(subject.getId(),coachIds);
        }
    }
    //分页查询
    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<Subject> page = subjectMapper.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public Subject findById(Integer id) {
        return subjectMapper.findById(id);
    }

    @Override
    public List<Integer> findSubjectAndCoachIds(Integer id) {
        return subjectMapper.findSubjectAndCoachIds(id);
    }

    @Override
    public void update(Subject subject, Integer[] coachIds) {
        //1.根据科目Id删除中间关系表
        subjectMapper.deleteAssciation(subject.getId());
        //2.重新建立中间关系
        setSubjectAndCoach(subject.getId(),coachIds);
        //3.更新科目数据
        subjectMapper.update(subject);
    }

    @Override
    public void deleteById(Integer id) {
        //1.先删除科目学员中间关系表
        subjectMapper.deleteAssciation(id);
        //2.根据id删除科目
        subjectMapper.deleteById(id);
    }

    @Override
    public List<Subject> findAll() {
        return subjectMapper.findAll();
    }

    //设置中间关系表
    private void setSubjectAndCoach(Integer id, Integer[] coachIds) {
        //创建map集合存储
        Map<String,Integer> map = new HashMap<>();
        for (Integer coachId : coachIds) {
            //添加科目id到map集合
            map.put("subject_id",id);
            //添加教练id到map集合
            map.put("coach_id",coachId);
            //将集合添加到数据库
            subjectMapper.setSubjectAndCoach(map);
        }
    }
}
